<?php
/**
 * ApiErrorHandler.php
 *
 * @author: cnx7 <zysafe@live.cn> 2021-01-31
 */

namespace common\domain\components;

use yii\web\Response;

class ApiErrorHandler extends \yii\web\ErrorHandler
{
    const ERROR_CODE = [
        1001,
        9000,
        9001,
        9002,
        9003,
    ];

    /**
     * Renders the exception.
     * @param \Exception $exception the exception to be rendered.
     * @throws \yii\base\ExitException
     */
    protected function renderException($exception)
    {
        $statusCode = $exception->statusCode ?? 500;

        $code = $exception->getCode();
        if ($code && in_array($code, static::ERROR_CODE)) {
            $statusCode = 200;
        }

        $data = [
            'msg' => $exception->getMessage(),
            'code' => $exception->getCode() ? $exception->getCode() : $statusCode
        ];

        if (YII_DEBUG) {
            $data = array_merge($data, [
                'file' => $exception->getFile() . ":" . $exception->getLine(),
                'trace' => $exception->getTraceAsString(),
            ]);
        }

        $res = \Yii::$app->response;
        $res->statusCode = $statusCode;
        $res->format = Response::FORMAT_JSON;
        $res->data = $data;
        $res->send();

        \Yii::$app->end();
    }
}
